<template>
	<view
		class="quantity-box"
		:style="{
			paddingTop: menuButton.top + 'px',
			background: deskConfig.linkUrl ? 'url(' + deskConfig.linkUrl + ')' : '#797979'
		}"
	>
		<view class="title" :style="{ lineHeight: menuButton.height + 'px' }">选择人数</view>

		<view class="default">
			<view
				class="default-top"
				:style="{
					fontSize: deskConfig.richSize ? deskConfig.richSize * 2 + 'rpx' : '30rpx',
					textAlign: deskConfig.richType ? deskConfig.richType : 'center'
				}"
				v-if="deskConfig.richName"
			>
				{{ deskConfig.richName }}
			</view>
			<view
				class="default-bottom pt-30"
				style="color: #e4e1d9; font-size: 50rpx"
				:style="{
					fontSize: deskConfig.linkSize ? deskConfig.linkSize * 2 + 'rpx' : '50rpx',
					textAlign: deskConfig.linkType ? deskConfig.linkType : 'center'
				}"
			>
				{{ deskConfig.linkName || '欢迎光临' }}
			</view>
		</view>

		<view class="checkQuantity">
			<view class="check-header">
				<text style="font-size: 34rpx">选择就餐人数</text>
				<text style="font-size: 30rpx; color: #bababa" v-if="desk.name">桌台号：{{ desk.name }}</text>
			</view>

			<scroll-view scroll-y style="height: 550rpx">
				<view class="check-header-number">
					<view v-for="item in numList" :key="item" :class="{ active: desk.person === item }" @click="onNumActive(item)">{{ item }}人</view>
					<view @click="onMore">更多</view>
				</view>

				<view class="select-box" v-if="reqLength > 0">
					必选
					<view class="required">
						<!-- <view class="select-box-children active" style="margin-top:20rpx;margin-right: 20rpx;">
						茶位费
					</view> -->
						<view class="select-box-children active" style="margin-top: 20rpx; margin-right: 20rpx" v-for="item in requiredFoodList" :key="item.id">
							{{ item.name }}
						</view>
					</view>
				</view>

				<view class="choosable select-box" v-if="optLength > 0">
					可选
					<view style="display: flex; justify-content: space-between; align-items: center; margin-top: 20rpx" v-for="(item, index) in optionalFoodList" :key="item.id">
						<view class="select-box-children" @click="onCkecked" :class="{ active: item.quantity >= 1 }">{{ item.name }}</view>
						<button
							v-if="item.quantity < 1"
							size="mini"
							style="height: 50rpx; border-radius: 25rpx; line-height: 50rpx; background-color: #f3c45d; color: #fff"
							@click="addNum(index)"
						>
							添加
						</button>

						<view v-else class="num-btn">
							<!-- v-show="number" v-show="number"-->
							<image src="/static/images/common/round_minus.png" class="minus-btn" @click="onReduce(index)"></image>
							<view class="number">{{ item.quantity }}</view>
							<image src="/static/images/common/round_add_normal.png" class="add-btn" @click="onAdd(index)"></image>
						</view>
					</view>
				</view>

				<!-- 	<view style="display: flex;justify-content: space-between;align-items: center;margin-top: 16px;">
						<view class="select-box-children">蘸料</view> -->
				<!-- 	<button type="primary" size="mini" style="height:50rpx;border-radius:25rpx;line-height:50rpx" >添加</button>  v-show="number" v-show="number"-->
				<!-- <view class="num-btn">
							<image src="/static/images/common/round_minus.png" class="minus-btn"></image>
							<view class="number">1</view>
							<image src="/static/images/common/round_add_normal.png" class="add-btn"></image>
						</view>
					</view>
					<view style="display: flex;justify-content: space-between;align-items: center;margin-top: 16px;">
						<view class="select-box-children">餐具</view>
						<button type="primary" size="mini" style="height:50rpx;border-radius:25rpx;line-height:50rpx">添加</button>
					</view>-->
			</scroll-view>
			<view style="height: 100rpx; padding: 20rpx" v-if="desk.id">
				<button v-if="system.hostName !== 'alipay'" type="primary" style="border-radius: 50rpx" @click="onsubmit">开始点餐</button>

				<view v-else style="padding: 0 100rpx">
					<u-button type="primary" shape="circle" @click="onsubmit">开始点餐</u-button>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
const app = getApp();
import { mapState, mapMutations } from 'vuex';
import { addNumbers } from '@/utils/number.js';
import common from '@/common/util.js';
export default {
	data() {
		return {
			desk: {
				openStatus: false
			}, // 后台返回桌台数据
			setting: {}, // 后台返回的门店数据
			numList: [1, 2, 3, 4, 5, 6, 7],
			bgImage: '', // 背景图
			optionalFoodList: [], // 必选参数
			requiredFoodList: [], // 可选参数
			openStatus: false,
			query: '', // 跳转的页面参数
			quantityScene: '',
			system: common.getSystemInfo()
		};
	},
	computed: {
		...mapState(['menuButton', 'token', 'scene']),
		...mapState('quantity', ['isSettlement', 'canteenConfig', 'commonScene', 'storeID']),
		reqLength() {
			return this.requiredFoodList.length;
		},
		optLength() {
			return this.optionalFoodList.length;
		},
		deskConfig() {
			if (this.canteenConfig) {
				return this.canteenConfig.deskConfig ? this.canteenConfig.deskConfig.setStyle : {};
			} else {
				return {};
			}
		}
	},
	onReady() {
		// #ifdef MP-ALIPAY
		uni.hideHomeButton();
		// #endif
	},
	methods: {
		...mapMutations(['MenuButton_Client', 'SET_ORDERID', 'SET_PERSON', 'SET_LOGIN', 'SET_SCENE', 'SET_STOCK', 'SET_PAGEDATA', 'SET_POPUP']),
		...mapMutations('quantity', ['CHANGE_isSettlement', 'SET_CANTEENDATA', 'SET_STOREID_Quantity']),
		...mapMutations('classify', ['SET_ClassifyConfig']),
		// 添加桌台
		async onsubmit() {
			if (!this.desk.person)
				return uni.showToast({
					title: '请选择就餐人数',
					icon: 'error'
				});
			const res = await this.$api.openDesk({
				person: this.desk.person,
				id: this.desk.id, // 桌台Id
				storeId: this.setting.storeId, // 门店id
				optionalFoodList: this.optionalFoodList,
				requiredFoodList: this.requiredFoodList,
				openStatus: this.openStatus
			});
			// console.log(res);
			// 开台时候存订单id

			if (this.desk.openStatus === 1) {
				this.SET_ORDERID(res.data.orderId), uni.setStorageSync('deskId', this.desk.id); // 将桌台Id存入本地
				uni.setStorageSync('orderId', res.data.orderId); // 将桌台Id存入本地
			}
			uni.switchTab({
				url: '/pages/tab_bar/classify/classify'
			});
		},
		// 获取列表
		async getPageList() {
			// uni.removeStorageSync('deskId')
			// 扫码拿到数据sence
			const res = await this.$api.scanCodesCanteen({
				code: 0,
				scene: this.scene
			});
			this.desk = res.data.desk;
			this.setting = res.data.setting;
			this.bgImage = res.otherData;
			this.optionalFoodList = res.data.desk.optionalFoodList || [];
			this.requiredFoodList = res.data.desk.requiredFoodList || [];
			this.openStatus = res.data.desk.openStatus; // 桌台状态
			this.SET_PERSON(res.data.desk.person);
			this.CHANGE_isSettlement(res.data.setting.isSettlement);

			if (this.query === 'isCart') return;
			// console.log(this.query);
			// 是否不用选择人数
			if (!res.data.setting.isSelectPerson) {
				if (res.data.setting.orderType === 1) {
					uni.removeStorageSync('deskId'); // 快餐模式将订单桌台Id移除
					uni.removeStorageSync('orderId');
					this.SET_ORDERID('');
				} else {
					uni.setStorageSync('deskId', this.desk.id); // 将桌台Id存入本地
					uni.setStorageSync('orderId', this.desk.orderId);
					this.SET_ORDERID(res.data.desk.orderId);
				}
				uni.switchTab({
					url: '/pages/tab_bar/classify/classify'
				});
				return;
			}

			// 状态为2 待下单
			if (res.data.desk.openStatus === 2) {
				this.SET_ORDERID(res.data.desk.orderId), uni.setStorageSync('deskId', this.desk.id); // 将桌台Id存入本地
				uni.setStorageSync('orderId', this.desk.orderId); // 将订单Id存入本地
				uni.switchTab({
					url: '/pages/tab_bar/classify/classify'
				});
				return;
			}
			// 状态为3 待结账
			if (res.data.desk.openStatus === 3) {
				this.SET_ORDERID(res.data.desk.orderId), uni.setStorageSync('deskId', this.desk.id); // 将桌台Id存入本地
				uni.setStorageSync('orderId', this.desk.orderId); // 将订单Id存入本地
				uni.redirectTo({
					url: '/pages/pay/pay_order/index'
				});
				return;
			}
			// 状态为4已结账
			if (res.data.desk.openStatus === 1 || res.data.desk.openStatus === 4) {
				this.SET_ORDERID(''), uni.removeStorageSync('deskId'); // 将桌台Id存入本地
				uni.removeStorageSync('orderId'); // 将桌台Id存入本地
				return;
			}
		},
		// 点击更多
		onMore() {
			if (this.numList.length >= 30)
				return uni.showToast({
					title: '没有那么多了',
					icon: 'error'
				});
			this.numList = addNumbers(this.numList);
		},
		// 选中人数
		onNumActive(num) {
			this.desk.person = num;
		},

		// 选中
		onCkecked() {
			this.isChecked = !this.isChecked;
		},
		// 添加按钮
		addNum(index) {
			this.optionalFoodList[index].quantity = 1;
		},

		// 加数字
		onAdd(index) {
			this.optionalFoodList[index].quantity++;
		},
		onReduce(index, quantity) {
			if (quantity <= 1) return;
			this.optionalFoodList[index].quantity--;
		},
		// onshow执行，要传回给pageconfig
		async getCommonCode(commonScene) {
			const q = decodeURIComponent(commonScene);
			const id = q.slice(q.indexOf('=') + 1);
			console.log(id, '解码');
			const res = await this.$api
				.getCodeDeskInfo({ id })
				.then((res) => {
					console.log(res, '解码');
					this.SET_SCENE(res.data.deskId + ',' + res.data.storeId);
					this.SET_STOREID_Quantity(res.data.storeId);
					if (uni.getStorageSync('scene') !== res.data.deskId + ',' + res.data.storeId) {
						uni.removeStorageSync('stock');
						uni.removeStorageSync('token');
						uni.removeStorageSync('userInfo');
					}
					// 调用页面的page传数据回去
					this.$api
						.GetDesignPageData({
							code: 'mobile_food',
							scene: res.data.deskId + ',' + res.data.storeId
						})
						.then((result) => {
							this.SET_STOCK(result.otherData); // 存储的stock
							this.SET_PAGEDATA(result.data.items); // 首页信息
							this.SET_POPUP(result.data.popUp && Array.isArray(result.data.popUp) ? result.data.popUp.map((item) => ({ ...item, isShow: true })) : []); // 首页信息
							this.SET_ClassifyConfig(result.data.classifyConfigData); // 购物车配置
							this.SET_CANTEENDATA(result.data.canteenConfig); // 开台页配置
						});
				})
				.catch((err) => {
					console.log(err);
					throw new Error('解码失败请重新扫码');
				});
		}
	},
	async mounted() {
		this.MenuButton_Client();
		setTimeout(async () => {
			const app = getApp().globalData;
			const systemInfo = common.getSystemInfo();
			// 如果是支付宝onlaunch，那么那普通码sence就在这里执行
			if (app.onLoadCommonScene && !app.onshowCommonScene) {
				console.log(app.onLoadCommonScene, 'onLoadCommonScene');
				await this.getCommonCode(app.onLoadCommonScene);
				app.onLoadCommonScene = null;
			}
			// 如果有值是onshow普通码
			if (app.onshowCommonScene) {
				console.log('onshowCommonScene', app.onshowCommonScene);
				await this.getCommonCode(app.onshowCommonScene);
			}
			this.quantityScene = uni.getStorageSync('scene');
			if (this.query !== 'isCart') {
				// 判断是否改变码，改变了调用登录，没改变不调用
				if (app.change) {
					const res = await uni.login();
					const login = await this.$api.OnLogin({
						code: res[1].code,
						appid: uni.getAccountInfoSync().miniProgram.appId,
						storeId: this.storeID || 0,
						scene: this.scene,
						type: systemInfo.hostName === 'alipay' ? 1 : 2 // 1是支付宝2是微信
					});
					this.SET_LOGIN({
						isLogin: true,
						token: login.data.auth.token,
						userInfo: login.data.user,
						systemAppId: login.data.systemAppId,
						stock: login.data.store,
						otherData: login.otherData
					});
					app.change = false;
				} else {
					let token = uni.getStorageSync('token') || '',
						systemAppId = uni.getStorageSync('systemAppId') || '',
						stock = uni.getStorageSync('stock') || '',
						userInfo = uni.getStorageSync('userInfo') || '',
						otherData = uni.getStorageSync('otherData') || '';
					if (token) {
						this.SET_LOGIN({
							isLogin: true,
							token: token,
							systemAppId: systemAppId,
							stock: stock,
							userInfo: userInfo,
							otherData: otherData
						});
					}
				}
			}
			this.getPageList();
		}, 200);
	},
	async onShow() {},
	onLoad(query) {
		// 跳转过来的页面参数
		console.log(query, 88888);
		this.query = query.cart;
		// this.MenuButton_Client()
		// // 1.判断是否登录，没有的话拦截到登录
		// if (!uni.getStorageSync('token')) {
		// 	uni.navigateTo({
		// 		url: '/pages/login/login'
		// 	})
		// 	uni.showToast({
		// 		title: '请先登录',
		// 		icon: 'error',
		// 	})
		// 	return
		// }
	}
};
</script>

<style lang="scss">
.quantity-box {
	width: 100%;
	height: 100vh;
	background: radial-gradient(#343635, #1d1c1a);

	.title {
		width: 100%;
		text-align: center;
		color: #fff;
	}

	.default {
		text-align: center;
		padding-top: 100rpx;
		color: #fff;
	}

	.checkQuantity {
		margin-top: 100rpx !important;
		padding: 20rpx;
		width: 680rpx;
		height: 800rpx;
		margin: 0 auto;
		background-color: #fff;
		border-radius: 15rpx;

		.check-header {
			display: flex;
			height: 100rpx;
			line-height: 100rpx;
			justify-content: space-between;
		}

		.check-header-number {
			display: flex;
			justify-content: space-between;
			flex-wrap: wrap;

			view {
				margin-top: 20rpx;
				height: 60rpx;
				min-width: 140rpx;
				background-color: #e7e8ea;
				text-align: center;
				line-height: 60rpx;
				border-radius: 10rpx;
			}
		}

		.required {
			display: flex;
			flex-wrap: wrap;
		}

		.select-box {
			padding-top: 30rpx;

			.select-box-children {
				padding: 0 20rpx;
				height: 55rpx;
				min-width: 140rpx;
				background-color: #e7e8ea;
				text-align: center;
				line-height: 55rpx;
				border-radius: 10rpx;
			}
		}
	}
}

.active {
	border: 1px solid #edac2e !important;
	color: #edac2e !important;
	background-color: #ffeecd !important;
}

// 数字
.num-btn {
	display: flex;
	min-width: 150rpx;
	justify-content: space-between;
	align-items: center;
	.add-btn,
	.minus-btn {
		width: 44rpx;
		height: 44rpx;
	}

	.number {
		font-size: 30rpx;
		width: 1.3rem;
		// height: 1.3rem;
		// line-height: 1.3rem;
		text-align: center;
		border-radius: 100%;
	}
}
</style>
